import re,sys,os,socket
from urllib2 import *
from threading import Thread
from Queue import Queue
import time,gzip,tempfile,string,random
from handler import handler

class sf_sub_handler(handler):
  def __init__(self):
    handler.__init__(self)
  def extract_url_lst(self,url):
    page=handler.try_to_read_url(self,url)
    if url.endswith("/"):url=url[:-1]
    if page==None:return []
    js_name_exp="src=\"(/Utility/[^\"].*%s\.js)\"" % url[url.rfind("/"):]
    js_name=re.findall(js_name_exp,page)[0]
    js_url=re.sub("/AllComic.*$",js_name,url)
    js=handler.try_to_read_url(self,js_url)
    return re.findall("picAy[\[\]\d =]*\"([^\"]*)\"",js)

class sf_handler(handler):
  def __init__(self):
    handler.__init__(self)
  def extract_url_lst(self,url):
    page=handler.try_to_read_url(self,url)
    page=page.replace("\n","")
    page=page.replace("\r","")
    l=re.findall("<ul class=\"serialise_list.*?</ul>",page)
    l="".join(l)
    res = re.findall("<a href=\"(.*?)\".*?>",l)
    res.reverse()
    return res
  def download_img(self,url,file_name):
    #  file name here is directory path
    if file_name.endswith(".jpg"):
      file_name=file_name[:file_name.rfind(os.path.sep)]
    if not os.path.exists(file_name):
      os.mkdir(file_name)
    from gallery_downloader import GD
    gd = GD(sf_sub_handler(),url,file_name,thread_num=10)
    gd.start_download()
